package com.leoman.service.impl;

import com.leoman.core.Constant;
import com.leoman.dao.LetterMoneyDao;
import com.leoman.entity.Letter;
import com.leoman.entity.LetterMoney;
import com.leoman.entity.User;
import com.leoman.exception.ParamErrorException;
import com.leoman.service.LetterMoneyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * LetterMoneyServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 3:59.
 */
@Service
public class LetterMoneyServiceImpl implements LetterMoneyService {

    @Autowired
    private LetterMoneyDao letterMoneyDao;

    @Override
    public List<LetterMoney> findAll() {
        return letterMoneyDao.findAll();
    }

    @Override
    public Page<LetterMoney> find(int pageNum, int pageSize) {
        return letterMoneyDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<LetterMoney> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public LetterMoney getById(int id) {
        return letterMoneyDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        letterMoneyDao.delete(id);
    }

    @Override
    public LetterMoney create(LetterMoney letterMoney) {
        return letterMoneyDao.save(letterMoney);
    }

    @Override
    public LetterMoney update(LetterMoney letterMoney) {
        return letterMoneyDao.save(letterMoney);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public Integer getMoneyLetter(Integer userId, Integer letterId) throws ParamErrorException {
        if (null == userId || null == letterId) {
            throw new ParamErrorException();
        }

        User user = new User();
        user.setId(userId);

        Letter letter = new Letter();
        letter.setId(letterId);

        LetterMoney letterMoney = letterMoneyDao.findOneByParams(userId, letterId);
        if (null == letterMoney) {
            letterMoney = new LetterMoney();

            letterMoney.setLetter(letter);
            letterMoney.setUser(user);

            letterMoneyDao.save(letterMoney);
        }

        return letterMoney.getId();
    }

    @Override
    public void changeMoneyStatus(Integer id) {
        LetterMoney letterMoney = letterMoneyDao.findOne(id);

        if (null != letterMoney && letterMoney.getMoneyStatus().equals(Constant.GIVE_MONEY_STATUS_NO)) {
            // 保存打赏记录
            letterMoney.setMoneyStatus(Constant.GIVE_MONEY_STATUS_YES);
            letterMoneyDao.save(letterMoney);
        }
    }
}